import { Controller, Post, Body, HttpCode, Request } from '@nestjs/common'
import { LoginService } from './login.service'
import { LoginDto, loginWithCodeDto } from './dto/login.dto'
import { Public } from '../../internal-modules/auth/decorators/public.decorator'
import { AuthService } from '../../internal-modules/auth/auth.service'

@Public()
@Controller('login')
export class LoginController {
  constructor(private readonly loginService: LoginService) {}

  @Post('send-code')
  async sendVerificationCode(
    @Body('email') email: string
  ): Promise<{ message: string }> {
    await this.loginService.sendVerificationCode(email)
    return { message: '验证码已发送到邮箱，有效期为5分钟' }
  }

  @Post()
  async login(
    @Body() data: LoginDto | loginWithCodeDto,
    @Body('type') type: 'password' | 'code'
  ) {
    if (type === 'password') {
      return this.loginService.loginWithPassword(data as LoginDto)
    } else if (type === 'code') {
      return this.loginService.loginWithCode(data as loginWithCodeDto)
    }
  }

  @Post('logout')
  @HttpCode(200)
  async logout(@Request() req): Promise<{ message: string }> {
    const token = AuthService.extractTokenFromHeader(req)
   
    token && (await this.loginService.logout(token))

    return { message: '退出登录成功' }
  }
}
